﻿using System;
using System.Collections.Generic;
using System.Web;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.web;
using System.Xml;

namespace TwentyTree4Umbraco
{
    public class VideoFileUploadHandler : IHttpHandler
    {
        #region IHttpHandler Members

        private const string DocTypeAlias = "WeAreVideo";
        private const int VidContainerID = 30351;
        private const string VidPropertyAlias = "Video";
        private const string Album = "554938";

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            HttpPostedFile file = context.Request.Files["Filedata"];
            string userguid = context.Request.Form["USERGUID"];
            string fileName = context.Request.Form["FILENAME"];

            if (!string.IsNullOrEmpty(userguid) && !string.IsNullOrEmpty(fileName))
            {
                DocumentType dt = DocumentType.GetByAlias(DocTypeAlias);
                
                Member mem = new Member(new Guid(userguid));

                Document d = Document.MakeNew(mem.Text + " - I'm Umbraco", dt, new umbraco.BusinessLogic.User(0), VidContainerID);

                string path = "/media/weare/" + d.Id.ToString();

                if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(path)))
                    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));

                string filename = file.FileName;
                string extension = filename.Substring(filename.LastIndexOf('.') + 1);
                filename = filename.Substring(0, filename.LastIndexOf('.') + 1);

                path = path + "/" + DateTime.Now.Ticks.ToString() + "_" + umbraco.cms.helpers.url.FormatUrl(filename) + "." + extension;

                d.getProperty("File").Value = path;
                d.getProperty("Member").Value = mem.Id;

                file.SaveAs(HttpContext.Current.Server.MapPath(path));


                string AlbumID = Album;

                List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();

                if (AlbumID != "")
                    list.Add(new KeyValuePair<string, string>("album_id", AlbumID));

                list.Add(new KeyValuePair<string, string>("title", mem.Text + " - I'm Umbraco"));

                string api_signature = Signature.Create(list);

                MultipartForm form;
                form = new MultipartForm("http://" + Config.GetSetting("domain") + "/api/photo/upload");
                form.FileContentType = "application/octet-stream";

                if (AlbumID != "")
                    form.setField("album_id", AlbumID);

                form.setField("title", mem.Text + " - I'm Umbraco");

                form.setField("api_signature", api_signature);
                form.sendFile(HttpContext.Current.Server.MapPath(path));
                string response = form.ResponseText.ToString();


                XmlDocument xd = new XmlDocument();
                xd.LoadXml(response);

                if (xd.SelectSingleNode("/response").Attributes["status"].Value == "ok")
                {
                    umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Custom,
                        d.Id, "Video uploaded to 23");

                    d.getProperty(VidPropertyAlias).Value = xd.SelectSingleNode("/response/photo_id").InnerText;
                }
                else
                {
                    umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Custom,
                       d.Id, "Failed to upload video to 23 " + xd.SelectSingleNode("/response").Attributes["message"].Value);

                }

            }
        }

        #endregion
    }
}
